<?php

$object = new MailServer();

$setting = [
    'log_file' => 'swoole.log',
    'worker_num' => 4, // 4个工作进程
    'task_worker_num' => 10, // 10个任务进程
];
$server = new swoole_server("127.0.0.1", 9501);
$server->set($setting);

$server->on('WorkerStart', array($object, 'onWorkerStart'));
$server->on('Connect', array($object, 'onConnect'));
$server->on('Receive', array($object, 'onReceive'));
$server->on('Close', array($object, 'onClose'));
$server->on('Task', array($object, 'onTask'));
$server->on('Finish', array($object, 'onFinish'));

$server->start();

class MailServer
{
    /** @var Mail */
    private $handle;

    public function __construct()
    {
        require 'Mail.php'; // PHPMailer邮件服务类
    }

    public function onWorkerStart($server, $workerId)
    {
        $mailConfig = require 'MailConfig.php'; // 发件人信息，重启时会重新加载配置文件
        $this->handle = new Mail($mailConfig);
    }

    public function onConnect($server, $fd, $reactorId)
    {

    }

    public function onReceive($server, $fd, $reactorId, $data)
    {
        
        $server->task($data); // 投递一个任务
        $return['code'] = 01;
        $return['msg'] = '投递一个邮件任务';
        
        $server->send($fd, json_encode($return));
    }

    public function onTask($server, $taskId, $workerId, $data)
    {
    	switch ($data)
    	{
    		case 1:
    		$mailData=[
    			'addtess'=>'xxxxx@163.com',
    			'subject'=>'单条邮件',
    			'body'=>'发送时间：'.date('Y-m-d H:i:s',time()),
    		];
    		$this->sendMail();
    		break;
    		
    		case 2:
    		$this->sendListMail();
    		break;
    		
    		default:
    		break;
    	}
    	
       
    }

    public function onFinish($server, $task_id, $data)
    {

    }

    public function onClose($server, $fd, $reactorId)
    {

    }
    
    //发送单个邮件
    protected function sendMail($data)
    {
    	 $data = json_decode($data, true);
         $this->handle->send($data['address'], $data['subject'], $data['body']); // 发送邮件
    }
    
    //群发邮件
    protected function sendListMail()
    {
    	$redis=new \Redis();
    	$redis->connect('127.0.0.1',6379);
    	
    	//swoole 定时器
    	swoole_timer_tick(60000, function($timer) use ($redis) { // 启用定时器，每1分钟执行一次
        $value = $redis->lpop('mailList');
        if($value)
        {
            //echo '获取redis数据:' . $value;
            $json = json_decode($value, true);
            $start = microtime(true);
            $data = json_decode($value, true);
            $rs = $this->handle->send($data['address'], $data['subject'], $data['body']); // 发送邮件
            $end = microtime(true);
            if ($rs) 
            {
                echo '发送成功！ 邮件标题：'.$data['subject'].', 耗时:'. round($end - $start, 3).'秒'.PHP_EOL;
            } 
            else 
            { // 把发送失败的加入到失败队列中，人工处理
                $redis->rpush("mailError", $value);
            }
        }
        else
        {
            swoole_timer_clear($timer); // 停止定时器
            echo "Emaillist出队完成";
        }
    });
    }
    
}
